package widgets

import (
	"path/filepath"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/y2h/fyne_poem/util"
)

func ListSlice(slice []string) *widget.List {
	return widget.NewList(func() int {
		return len(slice)
	}, func() fyne.CanvasObject {
		lbl := widget.NewLabel("aaaaaaaaaaaaaaa")
		lbl.Wrapping = fyne.TextWrapOff
		return lbl
	}, func(lii widget.ListItemID, co fyne.CanvasObject) {
		lbl := co.(*widget.Label)
		lbl.SetText(slice[lii])
	})
}
func ListBind(dataList binding.StringList) *widget.List {
	return widget.NewListWithData(dataList,
		func() fyne.CanvasObject {
			return widget.NewLabel("aaaaaaaaaaaaaaaaaaaaaaaaaa")
		}, func(di binding.DataItem, co fyne.CanvasObject) {
			lbl := co.(*widget.Label)
			lbl.Bind(di.(binding.String))
		})
}
func BtnLblList(dataList binding.StringList) *widget.List {
	return widget.NewListWithData(dataList,
		func() fyne.CanvasObject {
			return container.NewHBox(
				widget.NewButton("-", nil),
				widget.NewLabel("aaaaa"),
			)
		}, func(di binding.DataItem, co fyne.CanvasObject) {
			hbox := co.(*fyne.Container)
			btn := hbox.Objects[0].(*widget.Button)
			lbl := hbox.Objects[1].(*widget.Label)
			lbl.Bind(di.(binding.String))

			btn.OnTapped = func() {
				data, _ := dataList.Get()
				dataList.Set(util.Deletes(data, lbl.Text))
			}
		})
}

// List2Slice 用列表控件显示二维字符串切片
func List2Slice(dd [][]string) *widget.List {
	ldd := len(dd)
	lst := widget.NewList(func() int {
		return len(dd[0])
	}, func() fyne.CanvasObject {
		hbox1 := container.NewGridWithColumns(ldd)
		//hbox1 := container.NewHBox()
		for i := 0; i < ldd; i++ {
			hbox1.Add(widget.NewLabel("table"))
		}
		return hbox1
	}, func(lii widget.ListItemID, co fyne.CanvasObject) {
		box := co.(*fyne.Container)
		for i := 0; i < ldd; i++ {
			lbl := box.Objects[i].(*widget.Label)
			lbl.SetText(dd[i][lii])
		}
	})
	return lst
}
func DeleteList(dataList binding.StringList, f func()) *widget.List {
	return widget.NewListWithData(dataList,
		func() fyne.CanvasObject {
			return container.NewHBox(widget.NewLabel(""), layout.NewSpacer(),
				widget.NewButtonWithIcon("", theme.DeleteIcon(), nil))
		}, func(di binding.DataItem, co fyne.CanvasObject) {
			s := di.(binding.String)
			ss, _ := s.Get()
			hb := co.(*fyne.Container)
			lbl := hb.Objects[0].(*widget.Label)
			btn := hb.Objects[2].(*widget.Button)
			btn.OnTapped = func() {
				f()
			}
			lbl.SetText(filepath.Base(ss))

		})
}
